package com.xiexie.order.controller;

import com.xiexie.order.dto.SwAlarmDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Description 接收告警信息
 * @Date 2022-04-21 11:30
 * @Author xie
 */
@RestController
@RequestMapping("/alarm")
@RequiredArgsConstructor
@Slf4j
public class SwAlarmController {

    private final JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String from;


    /**
     * 接收告警信息
     *
     * @param alarmList
     */
    @PostMapping("/receive")
    public void receive(@RequestBody List<SwAlarmDTO> alarmList) {

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        // 发送者邮箱
        mailMessage.setFrom(from);
        // 接收者邮箱
        mailMessage.setTo(from);
        // 主题
        mailMessage.setSubject("告警邮件");
        String content = getContent(alarmList);
        //   邮件内容
        mailMessage.setText(content);

        sender.send(mailMessage);
        log.info("告警邮件已发送...");
    }

    private String getContent(List<SwAlarmDTO> alarmList) {

        StringBuilder sb = new StringBuilder();
        for (SwAlarmDTO dto : alarmList) {
            sb.append("scopeId: ").append(dto.getScopeId())
                    .append("\nscope: ").append(dto.getScope())
                    .append("\n目标Scope的实体名称: ").append(dto.getName())
                    .append("\nScope实体的ID: ").append(dto.getId0())
                    .append("\nid1: ").append(dto.getId1())
                    .append("\n告警规则名称: ").append(dto.getRuleName())
                    .append("\n告警消息内容: ").append(dto.getAlarmMessage())
                    .append("\n告警时间: ").append(dto.getStartTime())
                    .append("\n\n‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐\n\n");
        }

        return sb.toString();
    }

}
